package com.yuelao.netty.code;

import com.yuelao.netty.msg.Request;
import com.yuelao.netty.util.MarshallingCodeCFactory;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * Description
 *
 * @author fengliye
 * @version v1.0
 * @date 14/12/2018 15:14
 * @modify detail
 * 版本       修改人        修改时间      修改内容描述
 * ---------------------------------------------
 * <p>
 * ---------------------------------------------
 */
public class CodeClient {
    public static void main(String[] args) {

        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap b = new Bootstrap();
        b.group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel sc) throws Exception {
                        sc.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingDecoder());
                        sc.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingEncoder());
                        sc.pipeline().addLast(new CodeClientHandler());
                    }
                });

        try {
            ChannelFuture cf = b.connect("127.0.0.1", 8765).sync();

            for (int i = 0; i < 5; i++) {
                Request req = new Request();
                req.setId("" + i);
                req.setName("req" + i);
                req.setRequestMessage("数据信息" + i);
       /*         String path = System.getProperty("user.dir") + File.separatorChar + "feng.png";
                File file = new File(path);
                FileInputStream in = new FileInputStream(file);
                byte[] data = new byte[in.available()];
                in.read(data);
                in.close();
                req.setAttachment(GzipUtil.gzip(data)); //压缩*/
                cf.channel().writeAndFlush(req);
            }

            cf.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        group.shutdownGracefully();
    }

}
